package com.juyu.miliao.api.service;

import com.juyu.miliao.api.constant.QuestionAndAnswerTypeEnum;
import com.juyu.miliao.api.dao.mysql.QuestionBillInfoDao;
import com.juyu.miliao.api.dao.mysql.QuestionAndAnswerInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.QuestionAndAnswerInfo;
import com.juyu.miliao.api.domain.QuestionBillInfo;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.properties.MiLiaoApiProperties;
import com.juyu.miliao.api.rabbitMQ.QuestionAndAnswerRabbitMq;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;



/**
 * 问答信息service
 *
 * @author xuanqicheng
 * @create 2018-17-10:37 AM
 */
@Service
@Slf4j
public class QuestionAndAnswerInfoService {


    public static final Integer NUMBER_OF_GOLD_COINS_USED = 10;

    private static final Long ONE_DAY_BY_MILLISECOND = 86400000L;

    @Autowired
    private UserWalletDao userWalletDao;

    @Autowired
    private QuestionAndAnswerInfoDao questionAndAnswerInfoDao;

    @Autowired
    private QuestionAndAnswerRabbitMq questionAndAnswerRabbitMq;

    @Autowired
    private AppKeyService appkeyService;

    @Autowired
    private MiLiaoApiProperties miLiaoApiProperties;

    @Autowired
    private QuestionBillInfoDao questionBillInfoDao;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;


    /**
     * 创建提问信息
     * <p>
     * 1.先获取提问者用户的帐号钱包
     * 2.判断钱包金币是否大于或等于10个金币。
     * 3.如果金币小于10个金币，抛出金币不足异常
     *
     * @param questionAndAnswerInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void createInfo(QuestionAndAnswerInfo questionAndAnswerInfo) {

        UserWallet userWallet = userWalletDao.getUserWalletById(questionAndAnswerInfo.getQuestionUserId());

        log.info("用户：{},账号余额：{}", questionAndAnswerInfo.getQuestionUserId(), userWallet.getDeposit());
        if (userWallet.getDeposit() < NUMBER_OF_GOLD_COINS_USED) {

            throw new ConsumeRuntimeException("提问金币不足，请充值金币");
        }

        //设置 问题回答状态默认值
        questionAndAnswerInfo.setQuestionStatus(QuestionAndAnswerTypeEnum.QUESTION_NOT_ANSWER_TYPE.getCode());
        //设置回答审批状态
        questionAndAnswerInfo.setAnsweApprovalType(QuestionAndAnswerTypeEnum
                .ANSWER_NOT_EXAMINED_AND_APPROVED.getCode());

        questionAndAnswerInfo.setAnswerUrl("");

        questionAndAnswerInfo.setAnswerTime(0);

        questionAndAnswerInfo.setCreateTime(LocalDateTime.now());

        questionAndAnswerInfo.setCreateDate(LocalDate.now());

        //入库
        questionAndAnswerInfoDao.createInfo(questionAndAnswerInfo);

        UserWallet entity = new UserWallet();

        entity.setUserId(questionAndAnswerInfo.getQuestionUserId());

        entity.setDeposit(NUMBER_OF_GOLD_COINS_USED);

        // 减提问者金币
        userWalletDao.minusDeposit(entity);


        log.info("用户：{},消费10个金币之后的账号余额：{}", questionAndAnswerInfo.getQuestionUserId(),
                userWallet.getDeposit() - NUMBER_OF_GOLD_COINS_USED);

        /**
         * 保存消费记录
         *
         */

        QuestionBillInfo questionBillInfo = new QuestionBillInfo();

        questionBillInfo.setQuestionId(questionAndAnswerInfo.getId());

        questionBillInfo.setConsumerId(questionAndAnswerInfo.getQuestionUserId());

        questionBillInfo.setPaymentAmount(NUMBER_OF_GOLD_COINS_USED);

        questionBillInfo.setBeneficiaryId(questionAndAnswerInfo.getAnswerUserId());

        questionBillInfo.setProfitAmount(0.0);

        questionBillInfo.setStatus(1);

        questionBillInfo.setQuestionTime(questionAndAnswerInfo.getCreateTime());

        questionBillInfo.setCreateDate(questionAndAnswerInfo.getCreateDate());


        //账单入库：
        questionBillInfoDao.createQuestionBill(questionBillInfo);

        long time = miLiaoApiProperties.getTime().getQuestionExpireTime();

        questionAndAnswerRabbitMq.setQuestionAndAnswerInfo(Long.toString(time),
                Long.toString(questionAndAnswerInfo.getId()));


        //发送im消息给提问人
        String messageByAnswer = "你偷偷问她“"+questionAndAnswerInfo.getQuestionContent()+
                "”，请耐心等待她的回答，48小时后未回答金币返回账户~";

        vestRobotMessageService.questionCompletionSendMsg(questionAndAnswerInfo.getQuestionUserId(),messageByAnswer);

        Appkey appkey = appkeyService.getAppKeyByKey("giftRatio");
        // 金币转换钻石
        double diamond = DoubleFormatUtil.doubleFormate(
                NUMBER_OF_GOLD_COINS_USED * Double.parseDouble(appkey.getValue()));
        //发送im消息给主播
        String messageByAnchor = "对方给你发送了一个秘密提问“"+questionAndAnswerInfo.getQuestionContent()+
                "”，请在“秘密偷听-待回答”中回答，回答成功后可获得"+diamond+"钻石，回答时间要超过5s哟~";
        vestRobotMessageService.questionOrAnswerSendMsg(questionAndAnswerInfo.getAnswerUserId(),
                questionAndAnswerInfo.getQuestionUserId(),messageByAnchor);


    }

    @Transactional(rollbackFor = Exception.class)
    public void updateInfo(QuestionAndAnswerInfo questionAndAnswerInfo) {

        QuestionAndAnswerInfo obj = questionAndAnswerInfoDao.selectOne(questionAndAnswerInfo.getId());

        //设置 问题回答状态默认值
        questionAndAnswerInfo.setQuestionStatus(QuestionAndAnswerTypeEnum.QUESTION_TO_ANSWER_TYPE.getCode());
        //设置回答审批状态
        questionAndAnswerInfo.setAnsweApprovalType(QuestionAndAnswerTypeEnum
                .ANSWER_NOT_EXAMINED_AND_APPROVED.getCode());

        log.info("主播回答用户问题");


        if (obj != null && obj.getQuestionStatus() == QuestionAndAnswerTypeEnum.QUESTION_NOT_ANSWER_TYPE.getCode()) {


            //修改内容，并获取金币
            questionAndAnswerInfoDao.updateInfo(questionAndAnswerInfo);

            QuestionBillInfo questionBillInfo = questionBillInfoDao
                    .selectQuestionBillById(questionAndAnswerInfo.getId());

            Appkey appkey = appkeyService.getAppKeyByKey("giftRatio");

            // 金币转换钻石
            double diamond = DoubleFormatUtil.doubleFormate(
                    questionBillInfo.getPaymentAmount() * Double.parseDouble(appkey.getValue()));

            //设置账单信息
            questionBillInfo.setStatus(2);

            questionBillInfo.setProfitAmount(diamond);

            questionBillInfo.setAnswerTime(LocalDateTime.now());

            // 收款者，修改剩余钻石
            UserWallet inUserWallet = userWalletDao.getUserWalletById(questionAndAnswerInfo.getAnswerUserId());

            inUserWallet.setDiamond(diamond);

            userWalletDao.reviseDiamond(inUserWallet);

            log.info("主播：{}回答问题:{},获取钻石{}(等于10个金币)", questionAndAnswerInfo.getAnswerUserId(),
                    questionAndAnswerInfo.getId(), diamond);

            String sqlKey = "updateQuestionBillByAnswer";

            questionBillInfoDao.updateInfo(sqlKey,questionBillInfo);

            //主播回答之后，给用户发送消息
            String message = "我已回答了你偷问的小秘密“"+obj.getQuestionContent()+"”,快去“秘密偷听-已提问”中偷听吧~";

            vestRobotMessageService.questionOrAnswerSendMsg(obj.getQuestionUserId(),obj.getAnswerUserId(),message);

        } else {
            //只修改内容
            questionAndAnswerInfoDao.updateInfo(questionAndAnswerInfo);
            log.info("只修改内容");
        }

    }

    public QuestionAndAnswerInfo getEntity(Long id) {
        return questionAndAnswerInfoDao.getEntityById(id);
    }
}
